// Package auto
// @Author: zhangdi
// @File: go2ts
// @Version: 1.0.0
// @Date: 2023/8/28 13:50
package gen

import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"reflect"
	"strings"
)

// ConvertToTsI 将golang转成ts结构体
func ConvertToTsI(entity interface{}, saveDir string) string {
	t := reflect.TypeOf(entity).Elem()
	output := fmt.Sprintf("export interface %s {\n", t.Name())
	for i := 0; i < t.NumField(); i++ {
		field := t.Field(i)

		//构造字段名
		tag := field.Tag.Get("json")
		fieldName := strings.Split(tag, ",")[0]
		if fieldName == "" {
			fieldName = field.Name
		}
		//是否必填，根据omitempty来判断是否可为空
		if strings.Contains(field.Tag.Get("json"), "omitempty") {
			fieldName += "?"
		}
		output += fmt.Sprintf("\t%s: %s;\n", fieldName, toTypeScriptType(field.Type))

	}

	output += "}\n"

	entitName := reflect.TypeOf(entity).Elem().Name()
	filename := fmt.Sprintf("%s.ts", entitName)
	//判断文件夹saveDir是否存在，如果不存在则创建
	_, err := os.Stat(saveDir)
	if os.IsNotExist(err) {
		// 创建文件夹
		_ = os.MkdirAll(saveDir, os.ModePerm)
	}
	err = ioutil.WriteFile(filepath.Join(saveDir, filename), []byte(output), 0644)
	if err != nil {
		return "Error saving TypeScript interface:" + err.Error()
	}
	return output
}

// toTypeScriptType 类型映射转换
func toTypeScriptType(golangType reflect.Type) string {
	switch golangType.Kind() {
	case reflect.String:
		return "string"
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
		reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
		reflect.Float32, reflect.Float64:
		return "number"
	case reflect.Bool:
		return "boolean"
	case reflect.Array, reflect.Slice:
		return fmt.Sprintf("Array<%s>", toTypeScriptType(golangType.Elem()))
	default:
		return "any"
	}
}

func toTsTypeByString(golangType string) string {
	switch golangType {
	case "string":
		return "string"
	case "int", "int8", "int16", "int32", "int64",
		"uint", "uint8", "uint16", "uint32", "uint64",
		"float32", "float64":
		return "number"
	case "bool":
		return "boolean"
	case "[]string":
		return "string[]"
	default:
		return "any"
	}
}
